<template>
  <div class="app-container" v-loading="pageLoading" element-loading-text="加载中...">
    <el-card shadow="never">
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '备件编辑' : '备件添加' }}</span>
      </div>
      <el-form v-if="!pageLoading" ref="form" :model="form" :rules="rules" label-width="100px" size="small">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="备件编号" prop="partNo">
              <el-input v-model="form.partNo" placeholder="请输入备件编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备件名称" prop="partName">
              <el-input v-model="form.partName" placeholder="请输入备件名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格型号" prop="specNo">
              <el-input v-model="form.specNo" placeholder="请输入规格型号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备件类型" prop="partTypeCode">
              <el-select v-model="form.partTypeCode" placeholder="请选择备件类型" style="width: 100%">
                <el-option
                  v-for="type in partTypeOptions"
                  :key="type.code"
                  :label="type.name"
                  :value="type.code"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="备件仓库" prop="warehouseCode">
              <el-select v-model="form.warehouseCode" placeholder="请选择备件仓库" style="width: 100%" filterable>
                <el-option
                  v-for="w in warehouseOptions"
                  :key="w.warehouseCode || w.code || w.value"
                  :label="w.warehouseName || w.name || w.label"
                  :value="w.warehouseCode || w.code || w.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 关联资产 -->
        <div style="margin: 10px 0; font-weight: 600;">关联资产</div>
        <div style="margin-bottom: 10px; text-align: right;">
          <el-button type="primary" size="small" @click="showAssetSelector = true">快速选择</el-button>
        </div>
        <el-table :data="selectedAssets" size="mini" border>
          <el-table-column label="资产编号" prop="assetNo" width="140" />
          <el-table-column label="资产名称" prop="assetName" width="150" />
          <el-table-column label="位置" prop="location" width="120" />
          <el-table-column label="规格型号" prop="modelNo" width="120" />
          <el-table-column label="资产类型" prop="equipmentTypeCode">
            <template slot-scope="scope">
              {{ getEquipmentTypeName(scope.row.equipmentTypeCode) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="100" v-if="selectedAssets && selectedAssets.length > 0">
            <template slot-scope="scope">
              <el-button type="text" size="mini" @click="removeAsset(scope.row.id)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 备件图片 -->
        <ImageUpload
          ref="imageUpload"
          v-model="form.images"
          title="备件图片"
          :max-count="5"
          :max-size="2"
        />

        <div style="text-align: right; margin-top: 20px;">
          <el-button @click="handleCancel">返 回</el-button>
          <el-button type="primary" @click="handleSubmit">提 交</el-button>
        </div>
      </el-form>
    </el-card>

    <!-- 资产选择弹窗 -->
    <el-dialog title="快速选择资产" :visible.sync="showAssetSelector" width="800px" append-to-body>
      <AssetSelector :selected-assets="selectedAssets" @confirm="handleAssetSelect" @cancel="showAssetSelector=false" />
    </el-dialog>
  </div>
</template>

<script>
import AssetSelector from '@/views/components/AssetSelector.vue'
import ImageUpload from '@/views/components/ImageUpload.vue'
import { getPart, addPart, updatePart } from '@/api/inventory/part'
import { getToken } from '@/utils/auth'
import request from '@/utils/request'

export default {
  name: 'PartFormPage',
  components: { AssetSelector, ImageUpload },
  data() {
    return {
      pageLoading: true,
      showAssetSelector: false,
      selectedAssets: [],
      warehouseOptions: [],
      partTypeOptions: [],
      equipmentTypeOptions: [],
      _imageUrlsToInit: [],
      // 原始表单数据快照
      originalForm: null,
      form: {
        partNo: null,
        partName: null,
        specNo: null,
        partTypeCode: null,
        warehouseCode: null,
        enabled: 1,
        images: []
      },
      rules: {
        partNo: [{ required: true, message: '备件编号不能为空', trigger: 'blur' }],
        partName: [{ required: true, message: '备件名称不能为空', trigger: 'blur' }],
        specNo: [{ required: true, message: '规格型号不能为空', trigger: 'blur' }],
        partTypeCode: [{ required: true, message: '请选择备件类型', trigger: 'change' }],
        warehouseCode: [{ required: true, message: '请选择备件仓库', trigger: 'change' }]
      }
    }
  },
  computed: {
    isEdit() { return !!this.$route.params.partNo }
  },
  async created() {
    // 先加载所有字典，避免编辑模式下编码先显示后再变更
    await Promise.all([
      this.loadWarehouses(),
      this.loadPartTypes(),
      this.loadEquipmentTypes()
    ])
    await this.init()
    this.pageLoading = false
    await this.$nextTick()
    // 统一在表单渲染完成后初始化图片，避免 v-if 导致 ref 不存在
    if (this.$refs.imageUpload && Array.isArray(this._imageUrlsToInit)) {
      this.$refs.imageUpload.initFromUrls(this._imageUrlsToInit)
    }
  },
  methods: {
    loadWarehouses() {
      if (this.$warehouseLoaded) return Promise.resolve()
      return import('@/api/inventory/warehouse').then(mod => {
        const listFn = mod.listWarehouse || mod.list
        if (listFn) {
          return listFn({ pageNum: 1, pageSize: 9999 }).then(res => {
            this.warehouseOptions = res.rows || res.data || []
            this.$warehouseLoaded = true
          })
        }
      }).catch(() => { this.warehouseOptions = [] })
    },
    // 加载备件类型列表
    loadPartTypes() {
      if (this.$apiPartTypeLoaded) return Promise.resolve()
      return import('@/api/dict/partType').then(mod => {
        const listFn = mod.listPartType || mod.list
        if (listFn) {
          return listFn({ pageNum: 1, pageSize: 9999, enabled: 1 }).then(res => {
            this.partTypeOptions = res.rows || res.data || []
            this.$apiPartTypeLoaded = true
          })
        }
      }).catch(() => { this.partTypeOptions = [] })
    },
    // 加载设备类型列表
    loadEquipmentTypes() {
      if (this.$equipmentTypeLoaded) return Promise.resolve()
      return import('@/api/system/type').then(mod => {
        const listFn = mod.listType || mod.list
        if (listFn) {
          return listFn({ pageNum: 1, pageSize: 9999, enabled: 1 }).then(res => {
            this.equipmentTypeOptions = res.rows || res.data || []
            this.$equipmentTypeLoaded = true
          })
        }
      }).catch(() => { this.equipmentTypeOptions = [] })
    },
    init() {
      if (this.isEdit) {
        const partNo = this.$route.params.partNo
        return getPart(partNo).then(res => {
          this.form = { ...res.data }
          // 保存原始数据快照
          this.originalForm = { ...res.data }
          // 记录原编码
          this.form.oldPartNo = res.data.partNo
          this.selectedAssets = res.data.assets || []
          // 使用公共组件的方法初始化图片
          const urls = Array.isArray(res.data.imageUrls)
            ? res.data.imageUrls
            : (res.data.imageUrls ? (()=>{ try { return JSON.parse(res.data.imageUrls) } catch(e){ return [] } })() : [])
          // 暂存，等表单渲染后统一初始化
          this._imageUrlsToInit = urls
        })
      } else {
        // 新增模式下也保存初始表单状态
        this.originalForm = { ...this.form }
        return Promise.resolve()
      }
    },
    getEquipmentTypeName(code) {
      // 从设备类型选项中查找对应的名称
      const option = this.equipmentTypeOptions.find(item => item.code === code)
      return option ? option.name : code
    },
    removeAsset(id) {
      this.selectedAssets = this.selectedAssets.filter(a => a.id !== id)
    },
    handleAssetSelect(assets) {
      this.selectedAssets = assets
      this.showAssetSelector = false
    },
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (!valid) return
        // 使用公共组件的方法获取存储URL列表
        const imageUploadRef = this.$refs.imageUpload
        const storedList = imageUploadRef ? imageUploadRef.getStoredUrls() : []
        const payload = { ...this.form, assets: this.selectedAssets, imageUrls: JSON.stringify(storedList) }
        const action = this.isEdit ? updatePart : addPart
        action(payload).then(() => {
          this.$message.success(this.isEdit ? '修改成功' : '添加成功')
          // 延迟一下确保消息显示，然后关闭当前标签页并返回到上一页
          setTimeout(() => {
            // 关闭当前标签页
            this.$store.dispatch('tagsView/delView', this.$route)
            // 返回到上一页
            this.$router.back()
          }, 500)
        }).catch(error => {
          console.error('提交失败:', error)
          this.$message.error(this.isEdit ? '修改失败' : '添加失败')
        })
      })
    },
    handleCancel() {
      // 检查表单是否有更改
      if (this.originalForm) {
        // 创建当前表单数据副本用于比较
        const currentForm = { ...this.form }
        const originalForm = { ...this.originalForm }
        
        // 删除不需要比较的字段
        delete currentForm.images
        delete originalForm.images
        
        // 比较数据是否有变更
        const hasChanged = JSON.stringify(currentForm) !== JSON.stringify(originalForm)
        if (hasChanged) {
          this.$modal.confirm('内容没有保存，是否返回？').then(() => {
            this.$router.back()
          }).catch(() => {
            // 用户点击取消，不执行任何操作
          })
        } else {
          this.$router.back()
        }
      } else {
        this.$router.back()
      }
    }
  }
}
</script>
